<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28
 * Time: 16:15
 */

namespace app\index\server;


use app\index\model\Theme as ThemeModel;
use app\index\model\ThemeProduct as ThemeProductModel;
use app\lib\exception\DatabaseException;
use think\Exception;

class ThemeProductServer extends BaseServer
{
    public function getList($params = [])
    {
        $params = $this->prep_param($params);
        try {
            // 总条数
            $count = ThemeProductModel::count();
            $list = ThemeModel::order($params['sort'], $params['order'])
                ->limit($params['offset'], $params['limit'])
                ->select();
        } catch (Exception $e) {
            // 有些问题 应该抛出错误异常
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return bootstrap_table_return($count, $list);
    }

    public function detail($id)
    {
        try {
            $info = ThemeModel::with(['products'])
                ->where('id', '=', $id)
                ->find();
            if(!$info) {
                return setMsg(0, '查询失败');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, 'OK', $info);
    }

    public function delete($params = [])
    {
        try {
            $result = ThemeProductModel::where('theme_id', '=', $params['tid'])
                ->where('product_id', '=', $params['pid'])
                ->delete();
            if(!$result) {
                return setMsg(0, '删除失败');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '删除OK');
    }

    public function add($params = [])
    {
        // 查看主题是否存在
        $theme_exists = $this->theme_exists($params['theme_name']);
        if(!$theme_exists) {
            return setMsg(0, '对不起您输入的主题不存在');
        }
        $product_exists = $this->product_exists($params['product_name']);
        if(!$product_exists) {
            return setMsg(0, '对不起您输入的商品不存在');
        }
        $prep_data = [
            'theme_id' => $theme_exists->id,
            'product_id' => $product_exists->id
        ];
        try {
            $result = ThemeProductModel::insert($prep_data);
            if(!$result) {
                return setMsg(0, '添加主题-商品失败');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '添加主题-商品成功');
    }
}